import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Button, 
  Input, 
  DatePicker, 
  Table, 
  Switch,
  Typography,
  Avatar,
  Space,
  message,
  Modal,
  Form,
  Select,
  InputNumber  
} from 'antd';
import { 
  FilterOutlined,
  LeftOutlined,
  RightOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import styles from '../component/Student.module.css';
import { ActionPermissionGuard } from './PermissionGuard';

const { Search } = Input;
const { Text } = Typography;
const { RangePicker } = DatePicker;
const {Option}=Select

export default function Student() {
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [dateRange, setDateRange] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [students, setStudents] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 5,
    total: 0
  });
  const [form] = Form.useForm();

  // 获取学生数据
  const fetchStudents = async (params = {}) => {
    try {
      setLoading(true);
      
      // 检查用户是否已登录
      const currentUser = localStorage.getItem('currentUser');
      if (!currentUser) {
        console.error('用户未登录');
        return;
      }
      
      // 构建查询参数
      const queryParams = {
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...params
      };
      
      // 获取token
      const token = localStorage.getItem('token');
      if (!token) {
        console.error('用户未登录或token已过期');
        return;
      }
      
      // 调用API
      const response = await fetch(`http://localhost:3001/students?${new URLSearchParams(queryParams)}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (!response.ok) {
        if (response.status === 401) {
          console.error('获取学生列表失败: 认证失败');
          message.error('认证失败，请重新登录');
          return;
        }
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      
      if (result.data && result.pagination) {
        setStudents(result.data);
        setPagination({
          ...pagination,
          total: result.pagination.total
        });
      } else {
        console.error('获取学生列表失败: 响应格式错误');
        message.error('获取学生列表失败');
      }
    } catch (error) {
      message.error('获取学生列表失败');
      console.error('获取学生列表错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 初始加载数据
  useEffect(() => {
    fetchStudents();
  }, [pagination.current, pagination.pageSize]);

  // 处理筛选
  const handleFilter = () => {
    const params = {};
    if (searchText) params.name = searchText;
    if (dateRange && dateRange.length === 2) {
      params.startDate = dateRange[0].format('YYYY-MM-DD');
      params.endDate = dateRange[1].format('YYYY-MM-DD');
    }
    fetchStudents(params);
  };

  // 表格列定义
  const columns = [
    {
      title: '学生ID',
      dataIndex: 'studentId',
      key: 'studentId',
      width: 120,
      fixed: 'left'
    },
    {
      title: '学生姓名',
      dataIndex: 'name',
      key: 'name',
      width: 120,
      render: (text, record) => (
        <Space>
          <Text>{text}</Text>
        </Space>
      )
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      width: 80
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 120
    },
    {
      title: '所属年级',
      dataIndex: 'class',
      key: 'class',
      width: 100
    },
    {
      title: '成绩平均分',
      dataIndex: 'averageScore',
      key: 'averageScore',
      width: 120,
      render: score => `${score}分`
    },
    {
      title: '账户状态',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 100,
      render: (isActive) => (
        <Switch 
          checked={isActive}
          checkedChildren="启用"
          unCheckedChildren="禁用"
        />
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      render: (text,record) => {
        // 获取当前用户信息
        const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
        
        return (
          <Space size="middle">
            <ActionPermissionGuard action="edit" userId={currentUser.id}>
              <Button 
                type="text" 
                icon={<EditOutlined />} 
                className={styles.editBtn}
                onClick={() => handleEdit(record)}
              >
                编辑
              </Button>
            </ActionPermissionGuard>
            <ActionPermissionGuard action="delete" userId={currentUser.id}>
              <Button 
                type="text" 
                icon={<DeleteOutlined />} 
                className={styles.deleteBtn}
                onClick={() => confirmDelete(record)}
              >
                删除
              </Button>
            </ActionPermissionGuard>
          </Space>
        );
      }
    }
  ];

  const [editModalVisible, setEditModalVisible] = useState(false);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [currentStudent, setCurrentStudent] = useState(null);
  const [addForm] = Form.useForm();

  // 添加学生
  const handleAdd = () => {
    setAddModalVisible(true);
    addForm.resetFields();
  };

  // 提交添加
  const handleAddSubmit = async () => {
    try {
      const values = await addForm.validateFields();

      const token = localStorage.getItem('token');
      const response = await fetch('http://localhost:3001/students', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(values)
      });
      
      const result = await response.json();
      
      if (result.success) {
        message.success('学生添加成功');
        setAddModalVisible(false);
        addForm.resetFields();
        fetchStudents(); // 刷新列表
      } else {
        message.error(result.message || '添加失败');
      }
    } catch (error) {
      message.error('添加学生失败');
      console.error('添加学生错误:', error);
    }
  };

  // 编辑学生
  const handleEdit = (record) => {
    setCurrentStudent(record);
    setEditModalVisible(true);
  };

  // 提交编辑
  const handleEditSubmit = async () => {
    try {
      const values = await form.validateFields();
      const token = localStorage.getItem('token');
      const response = await fetch(`http://localhost:3001/api/students/${currentStudent._id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(values)
      });
      
      const result = await response.json();
      
      if (result.success) {
        message.success('学生信息更新成功');
        setEditModalVisible(false);
        fetchStudents(); // 刷新列表
      } else {
        message.error(result.message || '更新失败');
      }
    } catch (error) {
      message.error('更新学生信息失败');
      console.error('更新学生错误:', error);
    }
  };

  // 删除学生
  const handleDelete = async (id) => {
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`http://localhost:3001/api/students/${id}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      const result = await response.json();
      
      if (result.success) {
        message.success('学生删除成功');
        fetchStudents(); // 刷新列表
      } else {
        message.error(result.message || '删除失败');
      }
    } catch (error) {
      message.error('删除学生失败');
      console.error('删除学生错误:', error);
    }
  };

  // 确认删除弹窗
  const confirmDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除学生 ${record.name} 吗？此操作不可恢复！`,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => handleDelete(record._id),
      icon: <ExclamationCircleOutlined />
    });
  };

  // 分页变化
  const handleTableChange = (pagination) => {
    setPagination(pagination);
  };

  

  return (
    <div className={styles.studentContainer}>
      {/* 筛选区域 */}
      <Card 
        title="学员筛选" 
        bordered={false} 
        className={styles.filterCard}
      >
        <div className={styles.filterSection}>
          <div className={styles.filterItem}>
            <span className={styles.filterLabel}>注册时间：</span>
            <RangePicker 
              style={{ width: 240 }}
              value={dateRange}
              onChange={setDateRange}
            />
          </div>
          
          <Search
            placeholder="请输入学员账号、昵称、手机号"
            allowClear
            style={{ width: 280 }}
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            onSearch={handleFilter}
          />
          
          <Button 
            type="primary" 
            icon={<FilterOutlined />}
            onClick={handleFilter}
            loading={loading}
          >
            筛选
          </Button>
        </div>
      </Card>
      
      {/* 学生列表 */}
      <Card 
        title="学员列表" 
        bordered={false} 
        className={styles.listCard}
        extra={
          <ActionPermissionGuard action="add" userId={JSON.parse(localStorage.getItem('currentUser') || '{}').id}>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={handleAdd}
            >
              添加学员
            </Button>
          </ActionPermissionGuard>
        }
      >
        <Table
          columns={columns}
          dataSource={students}
          rowKey="_id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            pageSizeOptions: ['5', '10', '15', '20'],
            showTotal: total => `共 ${total} 条`,
            itemRender: (page, type, originalElement) => {
              if (type === 'prev') return <LeftOutlined />;
              if (type === 'next') return <RightOutlined />;
              return originalElement;
            }
          }}
          scroll={{ x: 1000 }}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
          }}
          onChange={handleTableChange}
        />
      </Card>

      {/* 编辑学生模态框 */}
      <Modal
        title="编辑学生信息"
        visible={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        onOk={handleEditSubmit}
        okText="保存"
        cancelText="取消"
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={currentStudent || {}}
        >
          <Form.Item
            label="学生姓名"
            name="name"
            rules={[{ required: true, message: '请输入学生姓名' }]}
          >
            <Input placeholder="请输入学生姓名" />
          </Form.Item>

          <Form.Item
            label="性别"
            name="gender"
            rules={[{ required: true, message: '请选择性别' }]}
          >
            <Select placeholder="请选择性别">
              <Select.Option value="男">男</Select.Option>
              <Select.Option value="女">女</Select.Option>
              <Select.Option value="其他">其他</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="手机号"
            name="phone"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            label="所属年级"
            name="class"
            rules={[{ required: true, message: '请选择年级' }]}
          >
            <Select placeholder="请选择年级">
              <Select.Option value="高一">高一</Select.Option>
              <Select.Option value="高二">高二</Select.Option>
              <Select.Option value="高三">高三</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="成绩平均分"
            name="averageScore"
            rules={[
              { required: true, message: '请输入成绩' },
              { type: 'number', min: 0, max: 100, message: '成绩必须在0-100之间' }
            ]}
          >
            <InputNumber 
              style={{ width: '100%' }}
              placeholder="请输入成绩平均分"
              precision={1} // 保留1位小数
            />
          </Form.Item>

          <Form.Item
            label="账户状态"
            name="isActive"
            valuePropName="checked"
          >
            <Switch
              checkedChildren="启用"
              unCheckedChildren="禁用"
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 添加学生模态框 */}
      <Modal
        title="添加学员"
        visible={addModalVisible}
        onCancel={() => setAddModalVisible(false)}
        onOk={handleAddSubmit}
        okText="添加"
        cancelText="取消"
        width={600}
      >
        <Form
          form={addForm}
          layout="vertical"
        >
          <Form.Item
            label="学生姓名"
            name="name"
            rules={[{ required: true, message: '请输入学生姓名' }]}
          >
            <Input placeholder="请输入学生姓名" />
          </Form.Item>

          <Form.Item
            label="性别"
            name="gender"
            rules={[{ required: true, message: '请选择性别' }]}
          >
            <Select placeholder="请选择性别">
              <Select.Option value="男">男</Select.Option>
              <Select.Option value="女">女</Select.Option>
              <Select.Option value="其他">其他</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="手机号"
            name="phone"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            label="所属年级"
            name="class"
            rules={[{ required: true, message: '请选择年级' }]}
          >
            <Select placeholder="请选择年级">
              <Select.Option value="高一">高一</Select.Option>
              <Select.Option value="高二">高二</Select.Option>
              <Select.Option value="高三">高三</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="成绩平均分"
            name="averageScore"
            rules={[
              { required: true, message: '请输入成绩' },
              { type: 'number', min: 0, max: 100, message: '成绩必须在0-100之间' }
            ]}
          >
            <InputNumber 
              style={{ width: '100%' }}
              placeholder="请输入成绩平均分"
              precision={1} // 保留1位小数
            />
          </Form.Item>

          <Form.Item
            label="账户状态"
            name="isActive"
            valuePropName="checked"
            initialValue={true}
          >
            <Switch
              checkedChildren="启用"
              unCheckedChildren="禁用"
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}